import apiClient from './interceptor';

// 文件接口的响应类型定义
export interface FileInfo {
  fileName: string;
  fileSize: number;
  uploadTime: string;
  downloadUrl?: string; // 可选的下载链接
}

export interface FileResponse {
  code: number;
  msg: string;
  data: FileInfo[];
}

// 添加附件信息的接口类型
export interface AttachmentInfo {
  fileName: string;
  contentType: string;
  fileSize: number;
}

export interface AttachmentResponse {
  code: number;
  msg: string;
  data: AttachmentInfo;
}

/**
 * 上传招聘公告附件
 * @param planId 招聘计划ID
 * @param file 要上传的文件
 * @param onProgress 进度回调函数
 * @returns Promise<FileResponse>
 * 
 * @example
 * const response = await uploadPlanAttachment(1, file);
 * if (response.code === 1) {
 *   // 上传成功
 * }
 */
export const uploadPlanAttachment = async (
  planId: number, 
  file: File,
  onProgress?: (percent: number) => void
) => {
  // 文件类型验证
  const allowedTypes = [
    'application/pdf',                                                    // PDF
    'application/msword',                                                // DOC
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // DOCX
    'application/vnd.ms-excel',                                          // XLS
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // XLSX
    'image/jpeg',                                                        // JPG/JPEG
    'image/png'                                                          // PNG
  ];
  
  if (!allowedTypes.includes(file.type)) {
    throw new Error('不支持的文件类型，仅支持PDF、Word、Excel和JPG/PNG图片格式');
  }

  // 文件大小验证（10MB）
  const maxSize = 10 * 1024 * 1024; // 10MB in bytes
  if (file.size > maxSize) {
    throw new Error('文件大小不能超过10MB');
  }

  const formData = new FormData();
  formData.append('planId', planId.toString());
  formData.append('attachments', file);

  try {
    const response = await apiClient.patch('/recruit/announcements/attachments', formData, {
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total && onProgress) {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress(percent);
        }
      },
    });
    return response.data;
  } catch (error) {
    throw error;
  }
};

/**
 * 下载招聘公告附件
 * @param planId 招聘计划ID
 * @returns Promise<any> 返回完整的响应，包含headers等信息
 */
export const downloadPlanAttachment = async (planId: number) => {
  try {
    const response = await apiClient.get('/recruit/announcements/download', {
      params: { planId },
      responseType: 'blob',
    });
    return response;
  } catch (error) {
    throw error;
  }
};

/**
 * 获取招聘公告附件信息
 * @param planId 招聘计划ID
 * @returns Promise<AttachmentResponse> 返回附件信息，不包含文件内容
 * 
 * @example
 * try {
 *   const response = await getPlanAttachmentInfo('1');
 *   if (response.code === 1) {
 *     const { fileName, contentType, fileSize } = response.data;
 *     // 处理附件信息
 *   }
 * } catch (error) {
 *   console.error('获取附件信息失败:', error);
 * }
 */
export const getPlanAttachmentInfo = async (planId: string): Promise<AttachmentResponse> => {
  try {
    const response = await apiClient.get(`/recruit/announcements/attachments/${planId}`);
    return response.data;
  } catch (error) {
    throw error;
  }
};

// 移除旧的获取附件列表方法，因为附件信息包含在招聘公告数据中 